package domotica.scontrol.rcp.gui.view;

import java.io.IOException;
import java.io.PrintStream;

import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;

import domotica.scontrol.rcp.ContentProvider;

public class OutputView extends PrintStream implements IOutputView {
	private ListViewer viewer;
	private Display display;
	private IOutputView outputView;
	
	public OutputView(Composite parent) {
		super(System.out, true);
		
		viewer = new ListViewer(parent);
		viewer.setContentProvider(new ContentProvider());
		display = parent.getDisplay();
		outputView = this;
		
		System.setOut(this);
		System.setErr(this);
	}
	
	public IOutputView getOutputView() {
		return outputView;
	}
	
	@Override
	public void println(String x) {
		addOutput(x);
	}
	
	@Override
	public void print(String s) {
		addOutput(s);
	}
	
	
//	@Override
//	public PrintStream printf(String format, Object... args) {
//		addOutput(String.format(format, args));
//		return super.printf(format, args);
//	}
//	
//	@Override
//	public PrintStream append(CharSequence csq) {
//		addOutput(csq.toString());
//		return super.append(csq);
//	}
	
	@Override
	public void write(byte[] arg0) throws IOException {
		addOutput(new String(arg0));
	}
	
	/*
	 * (non-Javadoc)
	 * Writes len bytes from the specified byte array starting at offset off to this stream. 
	 * If automatic flushing is enabled then the flush method will be invoked.
	 * Note that the bytes will be written as given; to write characters that will be 
	 * translated according to the platform's default character encoding, use the 
	 * print(char) or println(char) methods.
	 * @see java.io.PrintStream#write(byte[], int, int)
	 */
	@Override
	public void write(byte[] buf, int off, int len) {
		byte[] output = new byte[len];
		
		for(int i=off ; i < off+len ; i++) {
			output[i-off] = buf[i];
		}
		
		addOutput(new String(output));
	}
	
	public void dispose() {
		System.setOut(System.out);
		System.setErr(System.err);
	}

	public void addOutput(final String msg) {
		display.asyncExec(
			new Runnable() {
				public void run(){
					viewer.setInput(msg);
					viewer.reveal(viewer.getElementAt(viewer.getList().getItemCount()-1));
				}
			}
		);
	}
	
	public void setFocus() {
		display.getFocusControl().setFocus();
	}
}
